<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Form\OrderCancelActions;
use App\Admin\Actions\Form\OrderFinishActions;
use App\Admin\Actions\Grid\RowActions\BoundUserActions;
use App\Admin\Actions\Grid\RowActions\PayActions;
use App\Admin\Actions\Grid\Tools\CreateOrder;
use App\Admin\Actions\Grid\RowActions\PickOrder;
use App\Admin\Actions\Grid\RowActions\SendDataMessage;
use App\Admin\Actions\Grid\RowActions\SendDetailMessage;
use App\Admin\Actions\Grid\RowActions\SendMessage;
use App\Admin\Renderable\MessageRecordTable;
use App\Admin\Renderable\MessageTemplateTable;
use App\Admin\Repositories\Order;
use App\Models\AdminUser;
use App\Models\Category;
use App\Models\MessageRecord;
use App\Models\MessageTemplate;
use App\Models\OrderServiceProfile;
use App\Models\OrderServiceSubmitDetail;
use App\Models\User;
use App\Support\Data;
use App\Traits\ControllerHasTab;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Request;



class OrderController extends AdminController
{
    use ControllerHasTab;

    public function tab(): Row
    {
        $row = new Row();
        $tab = new Tab();
        $tab->add(Data::icon('record') . '订单管理', $this->renderGrid(), true);
        $tab->addLink(Data::icon('track') . '我的订单', admin_route('order.my.index'));
        // $tab->add(Data::icon('track') . '已处理事项', $this->renderGrid(), true, 2);
        $row->column(12, $tab);
        return $row;
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Order(['orderService', 'serviceEmail', 'serviceSystem', 'report', 'syntax', 'details', 'profiles', 'polish', 'user']), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->withBorder();
            $grid->disableCreateButton();
            $grid->disableViewButton();
            $grid->scrollbarX();
            $grid->column('id')->sortable();
            $grid->column('order_name');
            $grid->column('order_sn');
            $grid->column('created_at');
            $grid->column('order_status')->display(function ($status) {
                $state = Data::getOrderStatus();
                return $state[$status];
            });

            // $grid->column('order_customer')
            //     ->if(function ($column) {
            //         return $column->getValue();
            //     })
            //     ->then(function (Grid\Column $column) {
            //         $column->display(function ($id) {
            //             return AdminUser::find($id)->username ?? '';
            //         })->label();
            //     })
            //     ->else(function (Grid\Column $column) {
            //         $column->display('领取订单')->action(PickOrder::class);
            //     });

            $grid->column('is_carefree', '全程无忧客户')->select([0 => '否', 1 => '是'], true);

            $grid->column('service')->display(function ($ids) {
                if (empty($ids)) {
                    return '未选择服务';
                }
                $arr = Data::getOrderService();
                $ids = explode(',', $ids);
                $service = [];
                foreach ($ids as $key => $val) {
                    array_push($service, $arr[$val]);
                }
                return implode(',', $service);
            })->label()->width(20);
            $grid->column('order_amount');
            // $grid->column('user_id');
            $grid->column('pay_status')->display(function ($payStatus) {
                $arr = Data::getPayStatus();
                return $arr[$payStatus];
            });
            $grid->column('pay_amount');
            $grid->column('pay_type')->display(function ($payType) {
                $arr = Data::getPayType();
                // dd($payType);
                return isset($arr[$payType]) ? $arr[$payType] : '未知';
            });
            $grid->column('orderService.title', '论文标题')->limit(10);
            $grid->column('orderService.is_history', '拒稿历史')->using([0 => '无', 1 => '有'])
                ->dot(
                    [
                        0 => 'success',
                        1 => 'danger',
                    ]
                );
            $grid->column('orderService.history', '被拒期刊')->display(function ($history) {
                // $json2arr = json_decode($history, true);
                $json2arr = $history;
                if (!empty($json2arr)) {
                    // var_dump($json2arr);
                    $history = [];
                    foreach ($json2arr as $key => $val) {
                        array_push($history, $val['history_name']);
                    }
                    return $history;
                }
            })->implode(',')->limit(20);

            $grid->column('language')->display(function ($lang) {
                $arr = ['zh' => '中文', 'en' => '英文'];
                return isset($arr[$lang]) ? $arr[$lang] : '未选择';
            });
            // $grid->column('manuscript');
            // $grid->column('reference_file');
            $grid->column('additional')->limit(20);
            $grid->column('purpose')->display(function ($id) {
                $arr = Data::getOrderPurpose();
                return isset($arr[$id]) ? $arr[$id] : '';
            });
            $grid->column('subject_area')->display(function ($id) {
                return Category::find($id)->title ?? '';
            })->width(20);
            $grid->column('discipline')->display(function ($id) {
                return Category::find($id)->title ?? '';
            })->width(20);

            // $grid->column('updated_at')->sortable();
            $grid->column('user.realname', '用户名')->display(function ($name) {
                return $name ?? '未绑定';
            });
            $grid->column('user.phone', '手机号')->display(function ($phone) {
                return $phone ?? '未绑定';
            });

            $grid->column('report.review_report_rate', '查重报告')->help('客户自带是黄色填充') //;

                //     // ->display(2)->setAttributes(['style' => 'background:yellow']);
                ->if(function ($column) {

                    if ($this->orderService->is_review == 0) {
                        return true;
                    } else {
                        return false;
                    }
                })->then(function (Grid\Column $column) {
                    $column->display(function ($val) {
                        return "<span  style='background:yellow;display:block;width=20px;height=20px;'>$val %</span>";
                    });
                })->else(function (Grid\Column $column) {
                    $column->display($column->getValue() . ' %');
                });

            $grid->column('syntax.syntax_report_rate', '语法报告')->help('客户自带是黄色填充') //;

                // ->display(2)->setAttributes(['style' => 'background:yellow']);
                ->if(function ($column) {
                    if ($this->orderService->is_syntax == 0) {
                        return true;
                    } else {
                        return false;
                    }
                })->then(function (Grid\Column $column) {
                    $column->display(function ($val) {
                        return "<span  style='background:yellow;display:block;width=20px;height=20px;'>$val %</span>";
                    });
                })->else(function (Grid\Column $column) {
                    $column->display($column->getValue() . ' %');
                });

            $grid->column('orderService.bibliometric_report', '文献计量报告')->display(function ($report_time) {
                // var_dump($report_time);
                // $data = json_decode($report_time, 'true');
                return $report_time['bibliometric_report_time'] ?? '-';
            });

            $grid->column('orderService.journal_report', '期刊推荐报告')->display(function ($report_time) {
                // $data = json_decode($report_time, 'true');0
                return $report_time['journal_report_time'] ?? '-';
            });

            $grid->column('orderService.cover_page', '封面页')->display(function ($report_time) {
                // $data = json_decode($report_time, 'true');
                return $report_time['cover_page_time'] ?? '-';
            });

            $grid->column('orderService.contents_page', '目录页')->display(function ($report_time) {
                // $data = json_decode($report_time, 'true');
                return $report_time['contents_page_time'] ?? '-';
            });

            $grid->column('orderService.full_report', '完整报告')->display(function ($report_time) {
                // $data = json_decode($report_time, 'true');
                return $report_time['full_report_time'] ?? '-';
            });

            $grid->column('polish.polish_time', '润色/降重');
            $grid->column('orderService.is_target', '目标期刊')->using([0 => '无', 1 => '有'])
                ->dot(
                    [
                        0 => 'success',
                        1 => 'danger',
                    ]
                );
            $grid->column('orderService.target_journal', '期刊名单')->display(function ($target_journal) {
                // $json2arr = json_decode($target_journal, true);
                $json2arr = $target_journal;
                if (!empty($json2arr)) {
                    $target = [];
                    foreach ($json2arr as $key => $val) {
                        array_push($target, $val['target_journal_name']);
                    }
                    return $target;
                }
            })->implode(',')->width(30);

            $grid->column('serviceSystem', '投稿系统注册信息')->view('fileds_content');

            $grid->column('details', '投稿进度/投稿沟通tracking')->view('details_content');
            $grid->column('detailsRecord', '投稿进度发送记录')->display('投稿进度发送记录')->modal(function ($modal) {
                $modal->title('投稿进度发送记录');

                // 允许在闭包内返回异步加载类的实例
                return MessageRecordTable::make()->payload(['message_type' => 1]);
            });

            $grid->column('dataRecord', '补充资料发送记录')->display('补充资料发送记录')->modal(function ($modal) {
                $modal->title('补充资料发送记录');

                // 允许在闭包内返回异步加载类的实例
                return MessageRecordTable::make()->payload(['message_type' => 2]);
            });


            // 传入闭包
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new CreateOrder());
            });

            if (Admin::user()->isAdministrator()) {

                $grid->showEditButton();
                $grid->showDeleteButton();
                $grid->actions(function (Grid\Displayers\Actions $actions) {

                    // 支付按钮
                    if ($actions->row->pay_status == 0) {
                        $actions->append(new PayActions());
                    }
                    // 绑定客户按钮
                    if ($actions->row->user_id == null) {
                        $actions->append(new BoundUserActions());
                    }

                    // 分配
                    // if ($actions->row->order_customer == null) {
                    //     $actions->append(new BoundUserActions());
                    // }

                    $actions->append(new SendDetailMessage());
                    $actions->append(new SendDataMessage());


                    if ($actions->row->order_status == 0) {
                        // 完成
                        $actions->append(new OrderCancelActions());
                    } elseif ($actions->row->order_status == 1) {
                        // 取消
                        $actions->append(new OrderFinishActions());
                    }

                    // if ($actions->row->is_carefree == 1 || in_array(9, explode(',', $actions->row->service))) {
                    //     $actions->append(new IsCarefree());
                    // }
                });
            } else {
                $grid->disableActions();
            }


            $grid->filter(function (Grid\Filter $filter) {

                $filter->like('order_name');
                $filter->equal('order_sn');
                $filter->equal('pay_type')->select(Data::getPayType());
                $filter->equal('order_status')->select(Data::getOrderStatus());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Order(), function (Show $show) {
            $show->field('id');
            $show->field('order_sn');
            $show->field('order_name');
            $show->field('order_status');
            $show->field('order_customer');
            $show->field('order_amount');
            $show->field('username');
            $show->field('phone');
            $show->field('user_id');
            $show->field('pay_status');
            $show->field('pay_amount');
            $show->field('pay_type');
            $show->field('pay_ticket');
            $show->field('service');
            $show->field('language');
            $show->field('manuscript');
            $show->field('reference_file');
            $show->field('additional');
            $show->field('purpose');
            $show->field('subject_area');
            $show->field('discipline');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    protected function form()
    {
        return Form::make(new Order(['orderService', 'serviceEmail', 'serviceSystem', 'report', 'syntax', 'details', 'profiles', 'polish']), function (Form $form) {

            $form->hidden('is_carefree');

            $form->block(12, function (Form\BlockForm $form) {
                // $form->tools(function (Form\Tools $tools) use ($form) {

                //     if ($form->model()->order_status == 0) {
                //         // 完成
                //         $tools->append(new OrderCancelActions());
                //     } elseif ($form->model()->order_status == 1) {
                //         // 取消
                //         $tools->append(new OrderFinishActions());
                //     }
                // });
                // 设置标题
                $form->title('&nbsp;*&nbsp;订单信息');

                // $form->column(6, function (Form\BlockForm $form) {
                $form->display('id');
                $form->display('pay_status', '支付状态')->with(function ($value) {
                    $arr = Data::getPayStatus();
                    if ($value == 0) {
                        return $arr[$value];
                    } else {
                        return $arr[$value];
                    }
                });

                //  . '
                //         金额：' . $this->pay_amount  . '    支付凭证：' . '<img src="' . $this->pay_ticket . '" alt="支付凭证" width="150" height="120" />';
                $form->display('pay_amount', '支付金额');
                $form->image('pay_ticket', '支付凭证')->disable();
                $form->display('order_sn', '订单编号');
                $form->display('created_at', '订单生成时间');

                $form->checkbox('service', '服务信息')->options(Data::getOrderService())->canCheckAll()->saving(function ($value) {
                    // 也可以转化为json
                    return implode(',', $value);
                });
                $form->select('language', '语言')->options(['zh' => '中文', 'en' => '英文']);
                // });

                // $form->column(6, function (Form\BlockForm $form) {
                $form->textarea('additional', '额外指示');
                $form->select('purpose', '稿件用途')->options(Data::getOrderPurpose());
                $form->multipleFile('reference_file', '参考文件')->saveFullUrl()->autoUpload()->saving(function ($paths) {
                    // 也可以转化为json
                    return implode(',', $paths);
                });

                $form->select('subject_area', '学科领域')->options(
                    Category::where('parent_id', 0)->pluck('title', 'id')
                )
                    ->load('discipline', '/getOrderDiscipline');
                $form->select('discipline', '细分学科')->options(function ($id) {
                    return  Category::where('id', $id)->pluck('title', 'id');
                });
                // });

                // $form->column(12, function (Form\BlockForm $form) {

                // });
            });

            $form->block(12, function (Form\BlockForm $form) {

                $form->array('manuscript', '', function ($table) {
                    $table->file('manuscript_file', '上传稿件')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
                    $table->text('manuscript_number', '稿件字数');
                })->saving(function ($v) {
                    return json_encode($v);
                });
            });
            $form->block(12, function (Form\BlockForm $form) {
                // 设置标题
                $form->title('&nbsp;*&nbsp;服务信息');
                // 显示底部提交按钮
                // $form->showFooter();

                // 设置字段宽度
                // $form->width(9, 2);
                $form->column(12, function (Form\BlockForm $form) {

                    $form->text('order_name', '订单名称')->help('规则：企业-领域-客户姓名-工作内容');
                    $form->display('service', '服务内容')
                        ->with(function ($id) {
                            $service = Data::getOrderService();
                            $arr = [];
                            foreach (explode(',', $id) as $key => $val) {
                                array_push($arr, $service[$val]);
                            }
                            return implode(',', $arr);
                        });

                    $form->text('order_amount', '订单金额')->disable();
                    $form->text('orderService.title', '论文标题');

                    $form->divider();
                    $form->select('orderService.is_history', '拒稿历史')
                        ->options([0 => '无', 1 => '有'])
                        ->when(1, function (Form\BlockForm $form) {
                            $form->table('orderService.history', '', function ($table) {
                                $table->text('history_name', '拒稿期刊名');
                                $table->text('history_influence_factor', '影响因子');
                            });
                        });
                    $form->divider();

                    $form->select('orderService.is_target', '目标期刊')
                        ->options([0 => '无', 1 => '有'])
                        ->when(1, function (Form\BlockForm $form) {
                            $form->table('orderService.target_journal', '', function ($table) {
                                $table->text('target_journal_name', '期刊名');
                                $table->text('target_journal_influence_factor', '影响因子');
                            });
                        });
                });
            });
            if ($form->model()->is_carefree == 1) {
                $form->block(12, function (Form\BlockForm $form) {
                    $form->title('&nbsp;*&nbsp;全程无忧&投稿协助');
                    $form->select('is_carefree', '全程无忧客户')->options([0 => '否', 1 => '是']);
                });
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿邮箱信息');
                    $form->hasMany('serviceEmail', '', function ($form) {

                        $form->text('email', '投稿邮箱');
                        $form->text('password', '邮箱密码');
                    });
                });
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿系统注册信息');
                    $form->hasMany('serviceSystem', '', function ($form) {
                        $form->text('system_name', '系统名称');
                        $form->text('website', '网址');
                        $form->text('email', '邮箱');
                        $form->text('password', '密码');

                        $form->table('schedule', '投稿目标期刊', function ($table) {
                            $table->text('submit_reg_info_periodical', '期刊名');
                            $table->text('submit_reg_info_influence_factor', '影响因子');
                            $table->select('submit_reg_info_status', '投稿状态')->options([1 => '投稿中', 2 => '已接收', 3 => '被拒绝']);
                            $table->file('submit_reg_files', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                        })->saving(function ($v) {
                            return json_encode($v);
                        });
                    });
                });
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿详情');
                    $form->hasMany('details', '', function (Form\NestedForm $form) {
                        $form->switch('status', '发送短信')->help('设置为"不发短信”后，系统待办事项将不再进行该条沟通记录的发送提醒');
                        $form->datetime('datetime', '时间');
                        $form->textarea('contents', '内容');
                    });
                    // $form->divider();
                });
            } elseif (in_array(9, explode(',', $form->model()->service))) {
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿邮箱信息');
                    $form->hasMany('serviceEmail', '', function ($form) {
                        $form->text('email', '投稿邮箱');
                        $form->text('password', '邮箱密码');
                    });
                });
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿系统注册信息');
                    $form->hasMany('serviceSystem', '', function ($form) {
                        $form->text('system_name', '系统名称');
                        $form->text('website', '网址');
                        $form->text('email', '邮箱');
                        $form->text('password', '密码');

                        $form->table('schedule', '投稿目标期刊', function ($table) {
                            $table->text('submit_reg_info_periodical', '期刊名');
                            $table->text('submit_reg_info_influence_factor', '影响因子');
                            $table->select('submit_reg_info_status', '投稿状态')->options([1 => '投稿中', 2 => '已接收', 3 => '被拒绝']);
                            $table->file('submit_reg_files', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                        })->saving(function ($v) {
                            return json_encode($v);
                        });
                    });
                });
                $form->block(12, function (Form\BlockForm $form) {
                    $form->divider('投稿详情');
                    $form->hasMany('details', '', function (Form\NestedForm $form) {
                        $form->switch('status', '发送短信')->help('设置为"不发短信”后，系统待办事项将不再进行该条沟通记录的发送提醒');
                        $form->datetime('datetime', '时间');
                        $form->textarea('contents', '内容');
                    });
                });
            }


            #########################################################################################################
            // $form->block(12, function (Form\BlockForm $form) {

            //     $form->title('&nbsp;*&nbsp;全程无忧&投稿协助');

            //     if ($form->model()->is_carefree == 1) {
            //         // dd($form->model()->is_carefree);
            //         $form->select('is_carefree', '全程无忧客户')->when(1, function (Form\BlockForm $form) {
            //             $form->divider('投稿邮箱信息');
            //             $form->hasMany('serviceEmail', '', function ($form) {

            //                 $form->text('email', '投稿邮箱');
            //                 $form->text('password', '邮箱密码');
            //             });
            //             $form->divider('投稿系统注册信息');
            //             $form->hasMany('serviceSystem', '', function ($form) {
            //                 $form->text('system_name', '系统名称');
            //                 $form->text('website', '网址');
            //                 $form->text('email', '邮箱');
            //                 $form->text('password', '密码');

            //                 $form->table('schedule', '投稿目标期刊', function ($table) {
            //                     $table->text('submit_reg_info_periodical', '期刊名');
            //                     $table->text('submit_reg_info_influence_factor', '影响因子');
            //                     $table->select('submit_reg_info_status', '投稿状态')->options([1 => '投稿中', 2 => '已接收', 3 => '被拒绝']);
            //                     $table->file('submit_reg_files', '文件')->autoUpload()->url('users/files')->saveFullUrl();
            //                 })->saving(function ($v) {
            //                     return json_encode($v);
            //                 });
            //             });
            //             $form->divider('投稿详情');
            //             $form->hasMany('details', '', function (Form\NestedForm $form) {
            //                 $form->switch('status', '发送短信')->help('设置为"不发短信”后，系统待办事项将不再进行该条沟通记录的发送提醒');
            //                 $form->datetime('datetime', '时间');
            //                 $form->textarea('contents', '内容');
            //             });
            //             // $form->divider();
            //         })->options([0 => '否', 1 => '是']);
            //     } elseif (in_array(9, explode(',', $form->model()->service))) {
            //         // dd(in_array(9, explode(',', $form->model()->service)));
            //         $form->divider('投稿邮箱信息');
            //         $form->hasMany('serviceEmail', '', function ($form) {
            //             $form->text('email', '投稿邮箱');
            //             $form->text('password', '邮箱密码');
            //         });
            //         $form->divider('投稿系统注册信息');
            //         $form->hasMany('serviceSystem', '', function ($form) {
            //             $form->text('system_name', '系统名称');
            //             $form->text('website', '网址');
            //             $form->text('email', '邮箱');
            //             $form->text('password', '密码');

            //             $form->table('schedule', '投稿目标期刊', function ($table) {
            //                 $table->text('submit_reg_info_periodical', '期刊名');
            //                 $table->text('submit_reg_info_influence_factor', '影响因子');
            //                 $table->select('submit_reg_info_status', '投稿状态')->options([1 => '投稿中', 2 => '已接收', 3 => '被拒绝']);
            //                 $table->file('submit_reg_files', '文件')->autoUpload()->url('users/files')->saveFullUrl();
            //             })->saving(function ($v) {
            //                 return json_encode($v);
            //             });
            //         });
            //         $form->divider('投稿详情');
            //         $form->hasMany('details', '', function (Form\NestedForm $form) {
            //             $form->switch('status', '发送短信')->help('设置为"不发短信”后，系统待办事项将不再进行该条沟通记录的发送提醒');
            //             $form->datetime('datetime', '时间');
            //             $form->textarea('contents', '内容');
            //         });
            //         // $form->divider();
            //     }
            // });



            $form->block(12, function (Form\BlockForm $form) {
                // 设置标题
                $form->title('<span style="font-weight:blod">&nbsp;*&nbsp;完善报告</span>');
                // 显示底部提交按钮
                // $form->showFooter();
                // 设置字段宽度
                // $form->width(9, 2);
                $form->column(6, function (Form\BlockForm $form) {
                    $form->embeds('orderService.cover_page', '<h5 style="margin-left:10px">封面页</h5>', function ($form) {
                        $form->datetime('cover_page_time', '完成时间');
                        $form->file('cover_page_url', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                    });

                    $form->embeds('orderService.bibliometric_report', '<h5 style="margin-left:10px">计量报告</h5>', function ($form) {
                        $form->datetime('bibliometric_report_time', '完成时间');
                        $form->file('bibliometric_report_url', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                    });

                    $form->checkbox('orderService.is_review', '查重报告')->options([0 => '客户是否自带'])->when(0, function (Form\BlockForm $form) { //, 1 => '填写'
                        $form->datetime('report.review_report_time', '完成时间')->disable();
                    })->when('notIn', 0, function (Form\BlockForm $form) {
                        $form->datetime('report.review_report_time', '完成时间');
                    })->saving(function ($check) {
                        if (empty($check)) {
                            return null;
                        }
                        return implode(',', $check);
                    });

                    $form->rate('report.review_report_rate', '查重率');
                    $form->file('report.review_report_url', '文件')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
                    $form->checkbox('orderService.is_polish', '润色/降重')
                        ->options([0 => '客户是否自带']) //
                        ->when(0, function (Form\BlockForm $form) {
                            $form->datetime('polish.polish_time', '完成时间')->disable();
                        })->when('notIn', 0, function (Form\BlockForm $form) {
                            $form->datetime('polish.polish_time', '完成时间');
                        })->saving(function ($ckeck) {
                            if (empty($check)) {
                                return null;
                            }
                            return implode(',', $ckeck);
                        });
                    $form->file('polish.polish_url', '文件')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();


                    $form->file('orderService.author_info', '作者信息表')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
                });



                $form->column(6, function (Form\BlockForm $form) {

                    $form->embeds('orderService.contents_page', '<h5 style="margin-left:10px">目录页<h5>', function ($form) {
                        $form->datetime('contents_page_time', '完成时间');
                        $form->file('contents_page_url', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                    });
                    $form->embeds('orderService.full_report', '<h5 style="margin-left:10px">完整报告</h5>', function ($form) {
                        $form->datetime('full_report_time', '完成时间');
                        $form->file('full_report_url', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                    });

                    $form->checkbox('orderService.is_syntax', '语法报告')->options([0 => '客户是否自带'])->when(0, function (Form\BlockForm $form) { //, 1 => '填写'
                        $form->datetime('syntax.syntax_report_time', '完成时间')->disable();
                    })->when('notIn', 0, function (Form\BlockForm $form) {
                        $form->datetime('syntax.syntax_report_time', '完成时间');
                    })->saving(function ($check) {
                        if (empty($check)) {
                            return null;
                        }
                        return implode(',', $check);
                    });
                    $form->rate('syntax.syntax_report_rate', '查重率');
                    $form->file('syntax.syntax_report_url', '文件')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();



                    $form->table('orderService.journal_report', '期刊推荐报告', function ($table) {
                        $table->datetime('journal_report_time', '完成时间');
                        $table->file('journal_report_url', '文件')->autoUpload()->url('users/files')->saveFullUrl();
                    });
                });
            });


            $form->block(12, function (Form\BlockForm $form) {
                // 设置标题
                $form->title('&nbsp;*&nbsp;补充资料');
                // 显示底部提交按钮
                $form->showFooter();
                // 设置字段宽度
                // $form->width(9, 2);
                $form->column(12, function (Form\BlockForm $form) {
                    $form->hasMany('profiles', '', function ($table) {
                        $table->text('name', '说明')->required();
                        $table->text('files_name', '文件名称')->required();
                        $table->file('files', '文件')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
                        $table->textarea('contents', '沟通内容');
                        $table->text('customer_data_name', '客户资料名称');
                        $table->file('customer_data', '客户资料')->autoUpload()->move('medical/image/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
                    });
                });
            });
            $form->block(12, function (Form\BlockForm $form) {
                // 设置标题
                $form->title('&nbsp;*&nbsp;通知记录');
                // 显示底部提交按钮

                // 设置字段宽度
                // $form->width(9, 2);
                $form->column(12, function (Form\BlockForm $form) {
                    $data = MessageRecord::where('order_id', $form->getKey())
                        ->get(['user_id', 'message_id', 'message_type', 'admin_id', 'created_at'])
                        ->toArray();

                    foreach ($data as $key => &$val) {
                        $val['user_id'] = User::find($val['user_id'])->username ?? '';
                        if ($val['message_type'] == 1) {
                            $val['message_id'] = OrderServiceSubmitDetail::find($val['message_id'])->contents ?? '';
                            $val['message_type'] = '投稿详情（投稿进度）';
                        } elseif ($val['message_type'] == 2) {
                            $val['message_id'] = OrderServiceProfile::find($val['message_id'])->contents ?? '';
                            $val['message_type'] = '补充资料';
                        }
                        $val['admin_id'] = AdminUser::find($val['admin_id'])->username ?? '';
                    }

                    $form->html(new Card('通知记录', view('services_dashboard')
                        ->with('data', $data)));
                });
            });

            $form->saving(function (Form $form) {

                if ($form->input('is_carefree') == 1) {
                    $form->service = implode(',', array_unique(array_merge(explode(',', $form->model()->service), [8])));
                } elseif ($form->input('is_carefree') == 0) {

                    $form->service = implode(',', array_diff(explode(',', $form->model()->service), [8]));
                }

                if (in_array(8, explode(',', $form->input('service')))) {
                    $form->is_carefree = '1';
                } elseif ($form->input('is_carefree') == 0) {
                    $form->is_carefree = '0';
                }
            });
        });
    }


    public function getOrderDiscipline(Request $request)
    {
        $projectId = $request->get('q');
        return Category::where('parent_id', $projectId)->get(['id', DB::raw('title as text')]);
    }
}
